<?php
/**
 * SHOP 控制台首页
 * ============================================================================
 * 网络科技有限公司，并保留所有权利。
*/

define('IN_ZYS', true);
require(dirname(__FILE__) . '/includes/init.php');
//默认进来展示列表
if ($_REQUEST['act'] == 'list'){
    //商品高级搜索功能
	$cat_id = isset($_REQUEST['cat_id'])?$_REQUEST['cat_id']:0;//商品分类
	$brand_id = isset($_REQUEST['brand_id'])?$_REQUEST['brand_id']:0;//商品品牌
	$is_best = isset($_REQUEST['is_best'])?$_REQUEST['is_best']:0;//商品属性
	$is_on_sale = isset($_REQUEST['is_on_sale'])?$_REQUEST['is_on_sale']:2;//上架
    $user_id = isset($_REQUEST['shop_name'])?$_REQUEST['shop_name']:0;//店铺
    $keywords = isset($_REQUEST['keywords'])?$_REQUEST['keywords']:0;//店铺
    $arr=array();
    $arr['cat_id']=$cat_id;
    $arr['brand_id']=$brand_id;
    $arr['is_best']=$is_best;
    $arr['is_on_sale']=$is_on_sale;
    $arr['shop_name']=$user_id;
    $arr['keywords']=$keywords;
    $smarty->assign('sou',$arr);
	//商品分类
    $smarty->assign('cat_list',     cat_list(0, $cat_id));
	$smarty->assign('brand_list',   get_brand_list());
	//商品属性
	$ranks = $db->getAll("SELECT * FROM " .$zys->table('goods_sx') . "where del_status=0");
	$smarty->assign('ranks_list', $ranks);
    //店铺
    $shops = $db->getAll("SELECT * FROM " .$zys->table('shop') . "where del_status=0");
    $smarty->assign('shops_list', $shops);	
	$where=" where is_delete='0'";
	if($cat_id){$where.=" and cat_id='{$cat_id}'";}
    if($brand_id){$where.=" and brand_id='{$brand_id}'";}
    if($is_best){$is_best=",".$is_best.",";$where.=" and is_best like '%{$is_best}%'";}
    if($is_on_sale>=0 && $is_on_sale!=2){$where.=" and is_on_sale='{$is_on_sale}'";}
    if($user_id){$where.=" and user_id='{$user_id}'";}
    if($keywords){$where.=" and goods_name like '%{$keywords}%'";}
	$orderby=" order by goods_id desc";
	$sql="select goods_id,cat_id,user_id,goods_name,brand_id,goods_number,shop_price,goods_thumb,sort_order,is_on_sale from ".ly()."goods";
	$sql.=$where.$orderby;
	/*分页开始*/
	$num='10';
	$res=$db->query($sql);
	$total_count=$db->num_rows($res);
	$pagelist = new page(array('total'=>$total_count, 'perpage'=>$num));
	$currenpage=$pagelist->nowindex;
	$start=($currenpage-1)*$num;
	if ($total_count>$num){
		$smarty->assign('page',$pagelist->show(3));
	}else{
		$smarty->assign('page','');
	}
	$limit=" limit ".$start.','.$num;
	/*分页结束*/
	$sql.=$limit;
    $row=$db->getAll($sql);
    foreach ($row as $key => &$value) {
        if(goods_products($value['goods_id'])){
            $value['goods_products']='1';
        }
    }
    $smarty->assign('goods_info',$row);
    $smarty->display('goods_list.html');	
}elseif($_REQUEST['act']=='add'){
    //添加新商品
    $goods_id = isset($_REQUEST['goods_id'])?$_REQUEST['goods_id']:0;//商品ID
    //编辑商品
    if($goods_id){
        $sql="select * from ".ly()."goods where goods_id='{$goods_id}'";
        $goods=$db->getRow($sql);
        $goods['img_name']=substr($goods['goods_img'], strripos($goods['goods_img'],'/')+1);
        $cat_id=$goods['cat_id'];
        $sql="select r_id from ".ly()."shop where s_id='".$goods['user_id']."'";
        @$qy=$db->getRow($sql);
        //查询商品的图库
        $sql="select img_id,goods_id,img_desc,thumb_url,img_original from ".ly()."goods_gallery where goods_id='{$goods_id}'";
        $goods_imgs=$db->getAll($sql);
        $smarty->assign('goods_imgs',$goods_imgs);//分配商品图库
        $smarty->assign('qy',$qy);
        $smarty->assign('edit',$goods);
    }
	/*商户*/
	$ranksshop = $db->getAll("SELECT qy.* FROM ".ly()."shop_region qy,".ly()."shop sh where qy.r_id=sh.r_id and qy.r_del='0' and qy.r_zt='0' and sh.del_status='0' group by qy.r_id");
    $shop = $db->getAll("SELECT s_id,shop_name FROM ".ly()."shop where del_status=0 ");
	if($goods['user_id']){
		$smarty->assign('goods_usershid',admin_shname($goods['user_id']));
	}
	$smarty->assign('region_list',   $arrranks);
    $smarty->assign('shop_region',   $ranksshop);
	/*商品分类*/
    $sql="select * from ".ly()."category";
    $type=$db->getAll($sql);
    $smarty->assign('type',goods_type_cat($cat_id,$type));
	/*商品品牌*/
	$sql="select brand_id,brand_name from ".ly()."brand";
	$brand=$db->getAll($sql);
	$smarty->assign('brand',$brand);
    /*查询商品属性*/
    $sql="select id,name from ".ly()."goods_sx where del_status='0'";
    $sx=$db->getAll($sql);
    $smarty->assign('sx',$sx);
	/*商品类型*/
	$sql="select cat_id,cat_name from ".ly()."goods_type";
	$goods_type=$db->getAll($sql);
	$smarty->assign("goods_type",$goods_type);
	$smarty->assign("goods_attr_html",build_attr_html($goods['goods_type'],$goods['goods_id']));
    $smarty->display('goods_edit.html');
}elseif($_REQUEST['act']=='edit'){
    //编辑或添加商品提交
    $goods_id = isset($_REQUEST['goods_id'])?$_REQUEST['goods_id']:0;//商品ID
    $cat_id=isset($_POST['cat_id'])?$_POST['cat_id']:0;
    $user_id=isset($_POST['user_id'])?$_POST['user_id']:0;
    $goods_sn=isset($_POST['goods_sn'])?$_POST['goods_sn']:0;
    $goods_name=isset($_POST['goods_name'])?$_POST['goods_name']:0;
    $brand_id=isset($_POST['brand_id'])?$_POST['brand_id']:0;
    $shop_price=isset($_POST['shop_price'])?$_POST['shop_price']:0;
    $market_price=isset($_POST['market_price'])?$_POST['market_price']:0;
    $goods_desc=isset($_POST['goods_desc'])?$_POST['goods_desc']:0;
    $goods_weight=isset($_POST['goods_weight'])?$_POST['goods_weight']:0;
    $goods_number=isset($_POST['goods_number'])?$_POST['goods_number']:0;
    $warn_number=isset($_POST['warn_number'])?$_POST['warn_number']:0;
    $is_bests=isset($_POST['is_best'])?$_POST['is_best']:0;
    @$is_bests=implode(',', $is_bests);
    $is_best='0,'.$is_bests.',';
    $is_on_sale=isset($_POST['is_on_sale'])?$_POST['is_on_sale']:0;
    $is_alone_sale=isset($_POST['is_alone_sale'])?$_POST['is_alone_sale']:0;
    $keywords=isset($_POST['keywords'])?$_POST['keywords']:0;
    $goods_brief=isset($_POST['goods_brief'])?$_POST['goods_brief']:0;
    $seller_note=isset($_POST['seller_note'])?$_POST['seller_note']:0;
    $goods_type=isset($_POST['goods_type'])?$_POST['goods_type']:0;
    $attr_id_list=isset($_POST['attr_id_list'])?$_POST['attr_id_list']:0;
    $attr_value_list=isset($_POST['attr_value_list'])?$_POST['attr_value_list']:0;
    $attr_price_list=isset($_POST['attr_price_list'])?$_POST['attr_price_list']:0;
    $img_desc=isset($_POST['img_desc'])?$_POST['img_desc']:0;
    $img_url=isset($_POST['img_url'])?$_POST['img_url']:0;
    $add_time=time();
    //图片上传及等比例缩放
    @$file_url=$_FILES['goods_img'];
    if($file_url['error']==0){
        $goods_img=zoom_images($file_url);
    }
    if($goods_id){
        //编辑商品
        //查询商品原图及商品详情
        $sql="select original_img,goods_img,goods_thumb,goods_desc,goods_type from ".ly()."goods where goods_id='{$goods_id}'";
        $goods_rows=$db->getRow($sql);
        //先删除商品旧图
        if($file_url['error']==0){
            @unlink('../'.$goods_rows['original_img']);
            @unlink('../'.$goods_rows['goods_img']);
            @unlink('../'.$goods_rows['goods_thumb']);
        }
        //有新商品详情删除旧的商品详情
        if( $goods_desc){
            $str=$goods_rows['goods_desc'];
            //修改正则匹配先删除商品详情图片
            preg_match_all('/<img.*?src="(.*?)".*?>/is',$str,$arr);
            $drr=$arr['1'];
            $length=count($drr);
            for ($i=0; $i < $length; $i++) { 
                @unlink($drr[$i]);
            }
        }
        //修改语句时先判断有没有商品图片重新拼接sql语句
        $where=" where goods_id='{$goods_id}'";
        $sql="update ".ly()."goods set cat_id='{$cat_id}',user_id='{$user_id}',goods_sn='{$goods_sn}',goods_name='{$goods_name}',brand_id='{$brand_id}',goods_number='{$goods_number}',goods_weight='{$goods_weight}',market_price='{$market_price}',shop_price='{$shop_price}',warn_number='{$warn_number}',keywords='{$keywords}',goods_brief='{$goods_brief}',goods_desc='{$goods_desc}',is_on_sale='{$is_on_sale}',is_alone_sale='{$is_alone_sale}',add_time='{$add_time}',is_best='{$is_best}',goods_type='{$goods_type}',seller_note='{$seller_note}',last_update='{$add_time}'";
        if($goods_img['goods_img']){
            $sql.=",goods_thumb='{$goods_img['thumb_img']}',goods_img='{$goods_img['goods_img']}',original_img='{$goods_img['original_img']}'";
        }
        $sql.=$where;
        $res=$db->query($sql);
        if($res){
            //保存并判断商品属性入库
            if($goods_rows['goods_type']==$goods_type){
                $sql="select goods_attr_id,goods_id,attr_id from ".ly()."goods_attr where goods_id='{$goods_id}'";
                $goods_attr=$db->getAll($sql);
                $length=count($attr_id_list);
                for ($i=0; $i < $length; $i++) { 
                    foreach ($goods_attr as $key => $value) {
                        if($attr_id_list[$i]==$value['attr_id']){
                            $sql="update ".ly()."goods_attr set attr_id='".$attr_id_list[$i]."',attr_value='".$attr_value_list[$i]."',attr_price='".$attr_price_list[$i]."' where  goods_attr_id='".$value['goods_attr_id']."'";
                            $res=$db->query($sql);
                            unset($goods_attr[$key]);
                            unset($attr_id_list[$i]);
                            unset($attr_value_list[$i]);
                            unset($attr_price_list[$i]);
                        }
                    }   
                }
                @$goods_attr=array_values($goods_attr);
                @$attr_id_list=array_values($attr_id_list);
                @$attr_value_list=array_values($attr_value_list);
                @$attr_price_list=array_values($attr_price_list);
                if(!empty($goods_attr)){
                    foreach ($goods_attr as $k => $v) {
                        $sql="delete from ".ly()."goods_attr where goods_attr_id='".$v['goods_attr_id']."'";
                        $res=$db->query($sql); 
                    }
                }elseif(!empty($attr_id_list)){
                    $length=count($attr_id_list);
                    for ($i=0; $i < $length; $i++) { 
                        $sql="insert into ".ly()."goods_attr(goods_id,attr_id,attr_value,attr_price) values('{$goods_id}','".$attr_id_list[$i]."','".$attr_value_list[$i]."','".$attr_price_list[$i]."');";
                        $res=$db->query($sql); 
                    }   
                }
            }else{
                $sql="delete from ".ly()."goods_attr where goods_id='{$goods_id}'";
                $res=$db->query($sql);
                $length=count($attr_id_list);
                for ($i=0; $i < $length; $i++) { 
                    $sql="insert into ".ly()."goods_attr(goods_id,attr_id,attr_value,attr_price) values('{$goods_id}','".$attr_id_list[$i]."','".$attr_value_list[$i]."','".$attr_price_list[$i]."');";
                    $res=$db->query($sql); 
                }
            }     
        }else{
            $href[]=array('text'=>"重新编辑",'href'=>'history.back()');
            sys_msg("操作失败！",$href,false);
            exit;
        }
    }else{
        //添加新商品
        $sql="insert into ".ly()."goods(cat_id,user_id,goods_sn,goods_name,brand_id,goods_number,goods_weight,market_price,shop_price,warn_number,keywords,goods_brief,goods_desc,is_on_sale,is_alone_sale,add_time,is_best,goods_type,seller_note,last_update,goods_thumb,goods_img,original_img) values('{$cat_id}','{$user_id}','{$goods_sn}','{$goods_name}','{$brand_id}','{$goods_number}','{$goods_weight}','{$market_price}','{$shop_price}','{$warn_number}','{$keywords}','{$goods_brief}','{$goods_desc}','{$is_on_sale}','{$is_alone_sale}','{$add_time}','{$is_best}','{$goods_type}','{$seller_note}','{$add_time}','".$goods_img['thumb_img']."','".$goods_img['goods_img']."','".$goods_img['original_img']."')";
        $res=$db->query($sql);
        $goods_id=mysql_insert_id();
        if($res){
            $length=count($attr_id_list);
            for ($i=0; $i < $length; $i++) { 
                $sql="insert into ".ly()."goods_attr(goods_id,attr_id,attr_value,attr_price) values('{$goods_id}','".$attr_id_list[$i]."','".$attr_value_list[$i]."','".$attr_price_list[$i]."');";
                $res=$db->query($sql);
            }
        }
    }
    //商品是否存在属性对应库存
    $err=goods_products($goods_id);
	//处理图片（等比例缩放）
    if($_FILES['file_url']['error']['0']==0){
        $file_url=$_FILES['file_url'];
        $length=count( $file_url['name']);
        $arr=array();
        for ($i=0; $i < $length; $i++) {
            $brr=array(); 
            $brr['name']=$file_url['name'][$i];
            $brr['type']=$file_url['type'][$i];
            $brr['tmp_name']=$file_url['tmp_name'][$i];
            $brr['error']=$file_url['error'][$i];
            $brr['size']=$file_url['size'][$i];
            $arr[]=$brr;
        }   
        //图片上传及等比例缩放
        $length=count($arr);
        $crr=array();
        for ($i=0; $i < $length; $i++) { 
            $images_url=$arr[$i];
            if($images_url['error']==0){
                $image=zoom_images($images_url);
                $crr[]=$image;
            } 
        }
        $length=count($crr);
        for ($i=0; $i < $length; $i++) { 
            $sql="insert into ".ly()."goods_gallery(goods_id,img_url,img_desc,thumb_url,img_original) values('{$goods_id}','".$crr[$i]['goods_img']."','".$img_desc[$i]."','".$crr[$i]['thumb_img']."','".$crr[$i]['original_img']."')";
            $rs=$db->query($sql);  
        }
    }   
    //远程链接下载图片到本地及等比例缩放
    if($img_url['0']){
        $length=count($img_url);
        for ($i=0; $i < $length; $i++) { 
            $lujing=imgPath();
            $img_name=imgName();
            $arr=getImage($img_url[$i],$lujing,$img_name);
            if($arr){
                $original_img=substr($arr['save_path'],3);
                $goods_img=thumb("$original_img",400,400,'bg_');
                $thumb_img=thumb("$original_img",160,160,'sm_');
                $sql="insert into ".ly()."goods_gallery(goods_id,img_url,img_desc,thumb_url,img_original) values('{$goods_id}','{$goods_img}','".$img_desc[$i]."','{$thumb_img}','{$original_img}')";
                $rs=$db->query($sql);  
            }
        }
    }
    if($res){
        if(empty($err)){  
            $href[]=array('text'=>"返回商品列表",'href'=>'goods.php?act=list');
            sys_msg("操作成功！",$href);
        }else{
            //设置商品属性对应库存
            echo "<script>location.href='goods.php?act=products_list&goods_id=".$goods_id."'</script>";
        }
        
    }else{
        $href[]=array('text'=>"重新编辑",'href'=>'history.back()');
        sys_msg("操作失败！",$href,false);
    }
}elseif($_REQUEST['act']=='attr_ajax'){
    //获取商品对应类型的属性
	$cat_id=isset($_POST['cat_id'])?$_POST['cat_id']:0;//类型id
	$goods_id=isset($_POST['goods_id'])?$_POST['goods_id']:0;//商品id
	echo build_attr_html($cat_id,$goods_id);
}elseif($_REQUEST['act']=='edit_imgs'){
    //修改商品相册图片内容
    $zt=isset($_POST['zt'])?$_POST['zt']:0;//类型id
    $img_id=isset($_POST['id'])?$_POST['id']:0;//商品id
    $img_desc=isset($_POST['vals'])?$_POST['vals']:0;//商品id
    if($zt=="del"){
        //删除相册图片
        $sql="select img_url,thumb_url,img_original from ".ly()."goods_gallery where img_id='{$img_id}'";
        $rows=$db->getRow($sql);
        del_imgsUrl($rows['img_url']);
        del_imgsUrl($rows['thumb_url']);
        del_imgsUrl($rows['img_original']);
        $sql_x="delete from ".ly()."goods_gallery where img_id='{$img_id}'";
    }elseif($zt=="update"){
        //修改相册图片描述
        $sql_x="update ".ly()."goods_gallery set img_desc='{$img_desc}' where img_id='{$img_id}'";
    }
    $res=$db->query($sql_x);
    if($res){
        echo "1";
    }else{
        echo "2";
    } 
}elseif($_REQUEST['act']=='del_goods'){
    //删除商品到商品回收站
    $goods_id=isset($_REQUEST['goods_id'])?$_REQUEST['goods_id']:0;//类型id
    //删除商品
    $sql="update ".ly()."goods set is_delete='1' where goods_id='{$goods_id}'";
    $res=$db->query($sql);
    if(@$res){
        $href[]=array('text'=>"返回商品列表",'href'=>'goods.php?act=list');
        sys_msg("商品删除成功！",$href);
    }else{
        $href[]=array('text'=>"返回商品列表",'href'=>'goods.php?act=list');
        sys_msg("商品删除失败！",$href);
    }
}elseif($_REQUEST['act'] == 'ajax_sale'){
    //切换显示状态
    $goods_id=isset($_POST['goods_id'])?$_POST['goods_id']:0;
    $sale=isset($_POST['zt'])?$_POST['zt']:0;
    if($sale==1){$zt='0';}else{$zt='1';}
    $sql="update ".ly()."goods set is_on_sale='{$zt}' where goods_id='{$goods_id}'";
    $res=$db->query($sql);
    if($res){
        echo "1";   
    }else{
        echo "2";
    }
	
}elseif($_REQUEST['act'] == 'products_list1'){
	//查找商品属性设置库存
    $goods_id=isset($_GET['goods_id'])?$_GET['goods_id']:0;
    $sql="select goods_id,goods_name,goods_sn from ".ly()."goods where goods_id='{$goods_id}'";
    $goods=$db->getRow($sql);
    $smarty->assign("goods_products",goods_products($goods_id));
    $smarty->assign("goods",$goods);
    $smarty->display('goods_product.html');	
}elseif($_REQUEST['act'] == 'add_products'){
    //编辑商品属性对应的库存
    $product_sn=isset($_POST['product_sn'])?$_POST['product_sn']:0;
    $product_number=isset($_POST['product_number'])?$_POST['product_number']:0;
    $goods_attr=isset($_POST['goods_attr'])?$_POST['goods_attr']:0;
    $goods_id=isset($_POST['goods_id'])?$_POST['goods_id']:0;
    $length=count($product_number);
    //处理表单提交过来的数组数据
    for ($i=0; $i < $length; $i++) { 
        if($product_number[$i]=='' || $product_sn[$i]==''){
                unset($product_number[$i]);
                unset($product_sn[$i]);
                $len=count($goods_attr);
                for ($j=0; $j < $len; $j++) { 
                    unset($goods_attr[$j][$i]);
                }
        }
    }
    @$goods_attr=array_values($goods_attr);
    @$product_number=array_values($product_number);
    @$product_sn=array_values($product_sn);
    $length=count($product_number);
    $arr=array();
    for ($i=0; $i < $length; $i++) { 
        foreach ($goods_attr as $k => $v) {
            $arr[$i][]=$v[$i];
        }
    }
    $brr=array();
    for ($i=0; $i < $length; $i++) { 
        $brr[]=implode('|',$arr[$i]);
    }
    //查询商品数据库库存数据
    $sql="select * from ".ly()."products where goods_id='{$goods_id}'";
    $goods=$db->getAll($sql);
    $length=count($brr);
    //比对判断库存数据是否有修改
    for ($i=0; $i < $length; $i++) {
        foreach ($goods as $key => $value) {
           if($brr[$i]==$value['goods_attr']){
                $sql="update ".ly()."products set product_sn='".$product_sn[$i]."',product_number='".$product_number[$i]."' where product_id='".$value['product_id']."'";
                $res=$db->query($sql);
                unset($product_sn[$i]);
                unset($product_number[$i]);
                unset($brr[$i]);
                $str=0;
                foreach ($brr as $k => $v) {
                    if($value['goods_attr']!=$v){
                       $str+=0;
                    }else{
                       $str+=1;
                    }
                }
                if($str==0){
                    unset($goods[$key]);  
                }      
           }
        }
    }
    @$product_sn=array_values($product_sn);
    @$product_number=array_values($product_number);
    @$brr=array_values($brr);
    @$goods=array_values($goods);
    //对有变化的数据予以增加和删除
    if(!empty($brr)){
            $sql="select * from ".ly()."products where goods_id='{$goods_id}'";
            $goods_lists=$db->getAll($sql);
            $length=count($brr);
            for ($i=0; $i < $length; $i++) {
                foreach ($goods_lists as $key => $value) {
                     if($brr[$i]==$value['goods_attr']){
                        unset($brr[$i]);
                        unset($product_sn[$i]);
                        unset($product_number[$i]);
                     }
                }
                if($brr[$i]){
                    $sql="insert into ".ly()."products(goods_id,goods_attr,product_sn,product_number) values('{$goods_id}','".$brr[$i]."','".$product_sn[$i]."','".$product_number[$i]."')";
                    $res=$db->query($sql); 
                }                
            }
    }elseif(!empty($goods)){
            exit;
            foreach ($goods as $k => $v) {
                $sql="delete from ".ly()."products where product_id='".$v['product_id']."'";
                $res=$db->query($sql); 
            }
    }

    if($res){
        $href[]=array('text'=>"返回商品列表",'href'=>'goods.php?act=list');
        sys_msg("操作成功！",$href);
    }else{
        $href[]=array('text'=>"重新编辑",'href'=>'history.back()');
        sys_msg("操作失败！",$href,false);
    }
}elseif($_REQUEST['act'] == 'products_list'){
    //查找商品属性设置库存展示列表
    $goods_id=isset($_GET['goods_id'])?$_GET['goods_id']:0;
    $sql="select goods_id,goods_name,goods_sn from ".ly()."goods where goods_id='{$goods_id}'";
    $goods=$db->getRow($sql);
    $sql="select * from ".ly()."products where goods_id='{$goods_id}'";
    $product=$db->getAll($sql);
    foreach ($product as $key => &$value) {
        $value['goods_attr']=explode('|', $value['goods_attr']);
        $length=count($value['goods_attr']);
        for ($i=0; $i < $length; $i++) { 
            $sql="select goods_attr_id,attr_value from ".ly()."goods_attr where goods_attr_id='".$value['goods_attr'][$i]."'";
            $attrs=$db->getRow($sql);
            unset($value['goods_attr'][$i]);    
            $value['goods_attr'][$i]['id']=$attrs['goods_attr_id'];
            $value['goods_attr'][$i]['name']=$attrs['attr_value'];
        }
    }
    $smarty->assign("product",$product);
    $smarty->assign("goods_products",goods_products($goods_id));
    $smarty->assign("goods",$goods);
    $smarty->display('goods_products.html');    
}elseif($_REQUEST['act'] == 'batch_manage'){
    //商铺列表批量操作
    $goods_ids=isset($_POST['idx'])?$_POST['idx']:0;
    $type=isset($_POST['type'])?$_POST['type']:0;
    $cat_id=isset($_POST['catId'])?$_POST['catId']:0;
    $str=implode(',', $goods_ids);
    if($type==1){  
        $sql="update ".ly()."goods set is_delete='1' where goods_id in($str)";
    }elseif($type==2){
        $sql="update ".ly()."goods set is_on_sale='1' where goods_id in($str)";
    }elseif($type==3){
        $sql="update ".ly()."goods set is_on_sale='0' where goods_id in($str)";
    }elseif($type==4){
        $sql="update ".ly()."goods set cat_id='{$cat_id}' where goods_id in($str)";        
    }
    $res=$db->query($sql);
    if($res){
        $href[]=array('text'=>"返回商品列表",'href'=>'goods.php?act=list');
        sys_msg("批量操作成功！",$href);
    }else{
        $href[]=array('text'=>"返回商品列表",'href'=>'goods.php?act=list');
        sys_msg("批量操作失败！",$href);
    }
}elseif($_REQUEST['act'] == 'recycle_list'){
    //回收站搜索功能
    $keywords = isset($_REQUEST['keywords'])?$_REQUEST['keywords']:0;//店铺
    $sql="select goods_id,goods_name,goods_sn,shop_price,goods_thumb from ".ly()."goods where is_delete='1'";
    if($keywords){
        $smarty->assign("sou",$keywords);
        $sql.=" and goods_name like '%{$keywords}%'";
    }
    /*分页开始*/
    $num='10';
    $res=$db->query($sql);
    $total_count=$db->num_rows($res);
    $pagelist = new page(array('total'=>$total_count, 'perpage'=>$num));
    $currenpage=$pagelist->nowindex;
    $start=($currenpage-1)*$num;
    if ($total_count>$num){
        $smarty->assign('page',$pagelist->show(3));
    }else{
        $smarty->assign('page','');
    }
    $limit=" limit ".$start.','.$num;
    /*分页结束*/
    $sql.=$limit;
    $goods=$db->getAll($sql);
    $smarty->assign("goods",$goods);
    $smarty->display('goods_recycle.html');
}elseif($_REQUEST['act'] == 'recycle_edit'){
    $goods_id=isset($_GET['goods_id'])?$_GET['goods_id']:0;
    $sql="update ".ly()."goods set is_delete='0' where goods_id='{$goods_id}'";
    $res=$db->query($sql);
    if($res){
        $href[]=array('text'=>"返回商品回收站",'href'=>'goods.php?act=recycle_list');
        sys_msg("操作成功！",$href);
    }else{
        $href[]=array('text'=>"返回商品回收站",'href'=>'goods.php?act=recycle_list');
        sys_msg("操作失败！",$href);
    }
}elseif($_REQUEST['act'] == 'recycle_del'){
    //回收站移除商品
    $goods_id=isset($_GET['goods_id'])?$_GET['goods_id']:0;
    $res=dele_goods($goods_id);
    if($res){
        $href[]=array('text'=>"返回商品回收站",'href'=>'goods.php?act=recycle_list');
        sys_msg("操作成功！",$href);
    }else{
        $href[]=array('text'=>"返回商品回收站",'href'=>'goods.php?act=recycle_list');
        sys_msg("操作失败！",$href);
    }
}elseif($_REQUEST['act'] == 'batch_recycle'){
    $goods_ids=isset($_POST['idx'])?$_POST['idx']:0;
    $type=isset($_POST['type'])?$_POST['type']:0;
    $str=implode(',', $goods_ids);
    if($type==1){  
        $sql="update ".ly()."goods set is_delete='0' where goods_id in($str)";
        $res=$db->query($sql);
    }elseif($type==2){
        $length=count($goods_ids);
        for ($i=0; $i < $length; $i++) { 
            $res+=dele_goods($goods_idx[$i]);
        }
    }
    if($res){
        $href[]=array('text'=>"返回商品回收站",'href'=>'goods.php?act=recycle_list');
        sys_msg("批量操作成功！",$href);
    }else{
        $href[]=array('text'=>"返回商品回收站",'href'=>'goods.php?act=recycle_list');
        sys_msg("批量操作失败！",$href);
    }
}
//删除商品方法
function dele_goods($goods_id){
    $sql="select goods_desc,goods_thumb,goods_img,original_img from ".ly()."goods where goods_id='{$goods_id}'";
    $goods_rows=$GLOBALS['db']->getRow($sql);
    @unlink('../'.$goods_rows['original_img']);
    @unlink('../'.$goods_rows['goods_img']);
    @unlink('../'.$goods_rows['goods_thumb']);
    $goods_desc=$rows['goods_desc'];
    if( $goods_desc){
            //修改正则匹配先删除商品详情图片
            preg_match_all('/<img.*?src="(.*?)".*?>/is',$goods_desc,$arr);
            $drr=$arr['1'];
            $length=count($drr);
            for ($i=0; $i < $length; $i++) { 
                unlink($drr[$i]);
            }
    }
    $sql="delete from ".ly()."goods where goods_id='{$goods_id}'";
    $res=$GLOBALS['db']->query($sql);
    $sql="delete from ".ly()."goods_attr where goods_id='{$goods_id}'";
    $ress=$GLOBALS['db']->query($sql);
    $sql="select img_url,thumb_url,img_original from ".ly()."goods_gallery where goods_id='{$goods_id}'";
    $rows=$GLOBALS['db']->getAll($sql);
    $length=count($rows);
    for ($i=0; $i < $length; $i++) { 
        del_imgsUrl($rows[$i]['img_url']);
        del_imgsUrl($rows[$i]['thumb_url']);
        del_imgsUrl($rows[$i]['img_original']);
    }
    if($res){
        return "1";
    }else{
        return "0";
    }
}
//删除路径下的图片
function del_imgsUrl($img){
    unlink('../'.$img);
}
/*商品分类筛选调用*/
function goods_type_cat($p_id=false,$arr){
    $array=array();
    $array=$arr;
    $str="";
    foreach($arr as $v){
        if($v['parent_id']<1){
            if($p_id==$v['cat_id']){$select=" selected='selected'";}else{$select="";}
            $str.= "<option ".$select." value='".$v['cat_id']."'>".$v['cat_name']."</option>";
            $str.= goods_type_arr($v['cat_id'],$array,$p_id);
        }
    }
    return $str;
}
/*商品分类子级调用*/
function goods_type_arr($cat_id,$arr,$p_id=false,$nbsp=false){
    $array=array();
    $array=$arr;
    $str="";
    if($nbsp){
        $nbsp.="&nbsp;&nbsp;&nbsp;&nbsp;";
    }else{
        $nbsp="&nbsp;&nbsp;&nbsp;&nbsp;";
    }
    foreach($arr as $v){
        if($cat_id==$v['parent_id']){
            if($p_id==$v['cat_id']){$select=" selected='selected'";}else{$select="";}
            $str.= "<option ".$select." value='".$v['cat_id']."'>".$nbsp.$v['cat_name']."</option>";
            $str.= goods_type_arr($v['cat_id'],$array,$p_id,$nbsp);

        }
    }
    return $str;
}
/**
 * 根据属性数组创建属性的表单
 *
 * @access  public
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  string
 */
function build_attr_html($cat_id, $goods_id = 0){
	$attr = get_attr_list($cat_id, $goods_id);
	$html = '<table class="table tb-type2" cellpadding="0" cellspacing="0" width="100%" id="attrTable">';
    $spec = 0;
    foreach ($attr AS $key => $val)
    {
        $html .= "<tr><td class='firtd'>";
        if ($val['attr_type'] == 1 || $val['attr_type'] == 2)
        {
            $html .= ($spec != $val['attr_id']) ?
                "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" :
                "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
            $spec = $val['attr_id'];
        }

        $html .= "$val[attr_name]</td><td><input type='hidden' name='attr_id_list[]' value='$val[attr_id]' />";

        if ($val['attr_input_type'] == 0)
        {
            $html .= '<input name="attr_value_list[]" type="text" value="' .htmlspecialchars($val['attr_value']). '" size="40" /> ';
        }
        elseif ($val['attr_input_type'] == 2)
        {
            $html .= '<textarea name="attr_value_list[]" rows="3" cols="40">' .htmlspecialchars($val['attr_value']). '</textarea>';
        }
        else
        {
            $html .= '<select name="attr_value_list[]">';
            $html .= '<option value="">请选择...</option>';

            $attr_values = explode("\n", $val['attr_values']);

            foreach ($attr_values AS $opt)
            {
                $opt    = trim(htmlspecialchars($opt));

                $html   .= ($val['attr_value'] != $opt) ?
                    '<option value="' . $opt . '">' . $opt . '</option>' :
                    '<option value="' . $opt . '" selected="selected">' . $opt . '</option>';
            }
            $html .= '</select> ';
        }

        $html .= ($val['attr_type'] == 1 || $val['attr_type'] == 2) ?
            '属性价格： <input type="text" name="attr_price_list[]" value="' . $val['attr_price'] . '" size="5" maxlength="10" />' :
            ' <input type="hidden" name="attr_price_list[]" value="0" />';

        $html .= '</td></tr>';
    }

    $html .= '</table>';

    return $html;
	
}
/**
 * 取得通用属性和某分类的属性，以及某商品的属性值
 * @param   int     $cat_id     分类编号
 * @param   int     $goods_id   商品编号
 * @return  array   规格与属性列表
 */
function get_attr_list($cat_id, $goods_id = 0){
    if (empty($cat_id))
    {
        return array();
    }

    // 查询属性值及商品的属性值
    $sql = "SELECT a.attr_id, a.attr_name, a.attr_input_type, a.attr_type, a.attr_values, v.attr_value, v.attr_price ".
            "FROM " .$GLOBALS['zys']->table('attribute'). " AS a ".
            "LEFT JOIN " .$GLOBALS['zys']->table('goods_attr'). " AS v ".
            "ON v.attr_id = a.attr_id AND v.goods_id = '$goods_id' ".
            "WHERE a.cat_id = " . intval($cat_id) ." OR a.cat_id = 0 ".
            "ORDER BY a.sort_order, a.attr_type, a.attr_id, v.attr_price, v.goods_attr_id";

    $row = $GLOBALS['db']->GetAll($sql);
    return $row;
}
//图片上传及等比例缩放
function zoom_images($goods_img){
    $arr=array();
	require_once("../includes/upload_admin.php");//加载图片上传类
    $up=new upphoto;
    $up->get_ph_tmpname($goods_img['tmp_name']);
    $up->get_ph_type($goods_img['type']);
    $up->get_ph_size($goods_img['size']);
    $up->get_ph_name($goods_img['name']);
    $up->save();
    $original_img=$up->ph_name;
    $goods_img=thumb("$original_img",400,400,'bg_');
    $thumb_img=thumb("$original_img",160,160,'sm_');
    $arr['original_img']=$original_img;
    $arr['goods_img']=$goods_img;
    $arr['thumb_img']=$thumb_img;
    return $arr;
}
//图片上传及等比例缩放（调用示例）
// @$file_url=$_FILES['goods_img'];
// if($file_url['error']==0){
//     zoom_images($file_url);
// }
 

/*
 *商品属性对应库存
 */
function goods_products($goods_id){
    $sql="select r.goods_attr_id,r.attr_id,r.attr_value,e.attr_input_type,e.attr_type,e.attr_name from ".ly()."goods_attr r,".ly()."attribute e where r.attr_id=e.attr_id and goods_id='{$goods_id}'";
    $attrs=$GLOBALS['db']->getAll($sql);
    $length=count($attrs);
    $arr=array();
    for ($i=0; $i < $length; $i++) { 
        if($attrs[$i]['attr_type']!=0){
            $arr[]=$attrs[$i];
        }
    }
    $brr=array();
    $length=count($arr);
    for ($i=0; $i < $length; $i++) {
        if($arr[$i]){
            $brr[$i]['name']=$arr[$i]['attr_name'];
            $brr[$i]['val'][]=$arr[$i];
            unset($arr[$i]);
        }
        foreach ($arr as $k => $v) {
            if($brr[$i]['val'][0]['attr_id']==$v['attr_id']){ 
                $brr[$i]['val'][]=$v;
                unset($arr[$k]);
            }
        }
    }
    @$brr=array_values($brr);
    return $brr;
}


/*
*功能：php完美实现下载远程图片保存到本地
*参数：*文件url(必传),*保存文件目录(必传),*保存文件名称(必传)，使用的下载方式
*/
function getImage($url,$save_dir='',$filename='',$type=0){
  @$file = file_get_contents($url);
  $length=strlen($file);
  if($length==0){
      return false;
  }
  if(trim($url)==''){
 return array('file_name'=>'','save_path'=>'','error'=>1);
 }
 if(trim($save_dir)==''){
 $save_dir='./';
 }
  if($filename){//保存文件名
    $ext=strrchr($url,'.');
    if($ext!='.gif'&& $ext!='.jpg'){
  return array('file_name'=>'','save_path'=>'','error'=>3);
 }
    $filename=$filename.$ext;
    
  }
 if(0!==strrpos($save_dir,'/')){
 $save_dir.='/';
 }
 //创建保存目录
 if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
 return array('file_name'=>'','save_path'=>'','error'=>5);
 }
  //获取远程文件所采用的方法
 if($type){
	 $ch=curl_init();
	 $timeout=5;
	 curl_setopt($ch,CURLOPT_URL,$url);
	 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	 curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	 $img=curl_exec($ch);
	 curl_close($ch);
}else{
	ob_start();
	readfile($url);
	$img=ob_get_contents();
	ob_end_clean();
}
//$size=strlen($img);
//文件大小
$fp2=@fopen($save_dir.$filename,'a');
fwrite($fp2,$img);
fclose($fp2);
 unset($img,$url);
  return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
}
//文件路径
function imgPath(){
   $ph_url = "../uploadfile/image/"; 
   @$ymd = date("Ymd");//年月日
   $ph_path = $ph_url.$ymd.'/';
   return $ph_path;
}
//设置文件名
function imgName(){
 @$datetimes=date("YmdHis").'_'.rand(10000,99999);
 return $datetimes;
}

?>